<template>
  <div class="basic-info">
    <el-form ref="formRef" :model="formData" :rules="rules" label-width="100px" label-position="right">
      <!-- 第一行：课程名称、授课老师 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item :label="$t('course.courseName')" prop="name">
            <el-input v-model="formData.name" :placeholder="$t('common.inputPhTxt', [$t('course.courseName')])"
              clearable maxlength="50" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('course.teacher')" prop="instructors">
            <el-input v-model="formData.instructors" :placeholder="$t('common.inputPhTxt', [$t('course.teacher')])"
              clearable maxlength="50" />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第二行：出品方、科目分类 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item :label="$t('course.publisher')" prop="producer">
            <el-input v-model="formData.producer" :placeholder="$t('common.inputPhTxt', [$t('course.publisher')])"
              clearable maxlength="50" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('course.subjectCategory')" prop="subjectCategoryId">
            <el-tree-select v-model="formData.subjectCategoryId" :data="subjectCategoryTreeOptions" check-strictly
              :render-after-expand="false" clearable style="width: 100%"
              :placeholder="$t('common.selectPhTxt', [$t('course.subjectCategory')])" node-key="id"
              :props="{ label: 'name', value: 'id', children: 'children' }" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item :label="$t('course.courseCategory')" prop="courseCategory">
            <el-select v-model="formData.courseCategory"
              :placeholder="$t('common.selectPhTxt', [$t('course.courseCategory')])" clearable style="width: 100%">
              <el-option v-for="item in COURSE_CATEGORY_OPTIONS" :key="item.value" :label="item.label"
                :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第三行：课程概述 -->
      <el-row>
        <el-col :span="24">
          <el-form-item :label="$t('course.courseDescription')">
            <el-input v-model="formData.summary" type="textarea" :rows="4"
              :placeholder="$t('common.inputPhTxt', [$t('course.courseDescription')])" maxlength="500" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="24">
          <el-form-item :label="$t('course.courseIntroduction')" prop="introduction">
            <WangEditor v-model="formData.introduction" mode="default" :maxLength="2500" :scrollable="true"
              :placeholder="$t('common.inputPhTxt', [$t('course.courseIntroduction')])" class="mb-[20px]" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="24">
          <el-form-item :label="$t('course.courseHighlights')" prop="highlights">
            <WangEditor v-model="formData.highlights" mode="default" :maxLength="2500" :scrollable="true"
              :placeholder="$t('common.inputPhTxt', [$t('course.courseHighlights')])" class="mb-[20px]" />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第四行：课程图标 -->
      <el-row>
        <el-col :span="24">
          <el-form-item :label="$t('course.courseIcon')" prop="icon">
            <div class="flex flex-col items-start w-full">
              <!-- 文字描述在最上边 -->
              <div class="mb-3 w-full text-xs text-gray-600 leading-relaxed">
                <p class="mt-[5px]">{{ $t('courseMgr.uploadImageTip') }}</p>
              </div>
              <div class="w-full">
                <!-- 有图片时显示图片和删除按钮 -->
                <div v-if="imgUrl" class="relative w-32 h-32 group">
                  <img :src="imgUrl" class="w-32 h-32 block object-contain rounded-md border border-gray-300" />
                  <!-- 删除按钮，悬停时显示 -->
                  <div class="absolute inset-1 bg-black bg-opacity-50 flex
                     items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity duration-300">
                    <el-button :icon="Trash2" circle link @click="handleDeleteIcon"
                      class="!bg-black-500 !border-black-500 text-black !w-10 !h-10" />
                  </div>
                </div>
                <!-- 没有图片时显示上传区域 -->
                <el-upload v-else
                  class="border border-dashed border-gray-300 rounded-md cursor-pointer relative overflow-hidden transition-colors duration-300 w-32 h-32 flex items-center justify-center hover:border-blue-500"
                  :show-file-list="false" :before-upload="beforeIconUpload" :auto-upload="true"
                  :on-error="handleIconError" action="#" accept="image/*" :http-request="uploadIcon">
                  <el-icon class="text-3xl text-gray-400">
                    <Plus />
                  </el-icon>
                </el-upload>
              </div>
            </div>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, watch, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus } from '@vben/icons'
import { $t } from '#/locales/index.js'
import type { BasicInfoFormData, CourseItem } from './types'
import { Trash2 } from '@vben/icons'
import { obsUpload, obsDelete } from "#/utils/obs"
import { useRoute } from 'vue-router'
import { getImgUrl } from "#/utils/getImgUrl"
import { initBasicInfoFormData } from './types'
import { cloneDeep } from '@vben/utils'
import { safeMergeObject } from '#/utils/objectMerge'
import WangEditor from '#/components/editor.vue'
import { getSubjectCategoryTreeListsApi, type SubjectCategoryTreeNode } from '#/api/course'

interface Props {
  data?: CourseItem
}
const imgUrl = ref('')
// 科目分类树形选项
const subjectCategoryTreeOptions = ref<SubjectCategoryTreeNode[]>([])

// 课程类别选项
const COURSE_CATEGORY_OPTIONS = [
  { value: 'public_course', label: '公共课程' },
  { value: 'certification_course', label: '认证课程' }
]

const props = defineProps<Props>()
const emit = defineEmits<{
  'update:data': [data: BasicInfoFormData]
}>()
const formRef = ref()
const route = useRoute()
// 表单数据
const formData = reactive<BasicInfoFormData>(cloneDeep(initBasicInfoFormData))

// 表单校验规则
const rules = {
  name: [
    { required: true, message: $t('common.inputPhTxt', [$t('course.courseName')]), trigger: 'blur' }
  ],
  subjectCategoryId: [
    { required: true, message: $t('common.selectPhTxt', [$t('course.subjectCategory')]), trigger: 'change' }
  ],
  courseCategory: [
    { required: true, message: $t('common.selectPhTxt', [$t('course.courseCategory')]), trigger: 'change' }
  ],
  instructors: [
    { required: true, message: $t('common.inputPhTxt', [$t('course.teacher')]), trigger: 'blur' }
  ],
  producer: [
    { required: true, message: $t('common.inputPhTxt', [$t('course.publisher')]), trigger: 'blur' }
  ],
  summary: [
    { required: true, message: $t('common.inputPhTxt', [$t('course.courseDescription')]), trigger: 'blur' }
  ],
  icon: [
    { required: true, message: $t('common.selectPhTxt', [$t('course.courseIcon')]), trigger: 'change' }
  ],
  introduction: [
    { required: true, message: $t('common.inputPhTxt', [$t('course.courseIntroduction')]), trigger: 'blur' }
  ],
  highlights: [
    { required: true, message: $t('common.inputPhTxt', [$t('course.courseHighlights')]), trigger: 'blur' }
  ]
}

// 监听props变化，更新表单数据
watch(() => props.data, async (newData) => {
  if (newData) {
    // 编辑模式：根据 formData 的结构获取数据
    safeMergeObject(formData, newData)
    // emit('update:data', { ...formData })
    if (newData?.icon) {
      // 如果有图标路径，从 OBS 加载图片
      try {
        const imgData = await getImgUrl(newData.icon)
        if (imgData instanceof ArrayBuffer) {
          // 将二进制数据转换为 Blob
          const blob = new Blob([imgData], { type: 'image/png' })
          imgUrl.value = URL.createObjectURL(blob)
        }
      } catch (err) {
        console.error($t('courseMgr.loadImageFail'), err)
        ElMessage.error($t('courseMgr.loadImageFail'))
      }
    }
  } else {
    // 新增模式：重置为空
    Object.assign(formData, {
      name: '',
      instructors: '',
      producer: '',
      summary: '',
      icon: ''
    })
  }
}, { immediate: true })

// 监听表单数据变化，向父组件发送数据
watch(() => formData, (newData) => {
  emit('update:data', { ...newData })
}, { deep: true })

// 图标上传前的校验
const beforeIconUpload = (file: File) => {
  const allowedTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/bmp']
  const isValidFormat = allowedTypes.includes(file.type)
  const isLt5M = file.size / 1024 / 1024 < 5

  if (!isValidFormat) {
    ElMessage.error('仅支持bmp、png、jpeg、jpg格式图片')
    return false
  }
  if (!isLt5M) {
    ElMessage.error($t('common.imageSizeLimitTxt', ['5']))
    return false
  }
  return true
}

// 图标上传失败
const handleIconError = () => {
  ElMessage.error($t('common.uploadFailTxt'))
}

// 自定义上传方法
const uploadIcon = ({ file }: any) => {
  // 获取路由第一层路径（去掉开头的/）
  // 暂时使用本地URL预览
  imgUrl.value = URL.createObjectURL(file)
  // 上传到 OBS，使用路由路径作为前缀
  obsUpload({
    Key: file.name,
    SourceFile: file
  }, (err: any, result: any, key: string) => {
    if (err) {
      ElMessage.error($t('common.uploadFailTxt'))
      return
    }
    // 上传成功后更新表单数据
    formData.icon = key
    formRef.value?.clearValidate(['icon'])
    ElMessage.success($t('common.uploadSuccessTxt'))
  })

  return Promise.resolve()
}

// 删除图标
const handleDeleteIcon = () => {
  if (formData.icon) {
    obsDelete({
      Key: formData.icon
    }, (err: any, result: any) => {
      if (err) {
        ElMessage.error($t('courseMgr.deleteFail'))
        return
      }
      imgUrl.value = ''
      formData.icon = ''
      ElMessage.success($t('common.deleteSuccessTxt'))
    })
  }

}

// 表单校验方法
const validate = async () => {
  return await formRef.value?.validate()
}

// 重置表单
const resetForm = () => {
  imgUrl.value = ''
  formRef.value?.resetFields()
}

// 获取科目分类树形数据
const loadSubjectCategoryTree = async () => {
  try {
    const data = await getSubjectCategoryTreeListsApi()
    subjectCategoryTreeOptions.value = data || []
  } catch (error) {
    console.error('获取科目分类树形数据失败:', error)
    ElMessage.error('获取科目分类数据失败')
  }
}

// 组件挂载时加载数据
onMounted(() => {
  loadSubjectCategoryTree()
})

// 暴露方法给父组件
defineExpose({
  validate,
  resetForm
})
</script>
